package com.kusej.idno.generation;

import com.intellij.openapi.ui.Messages;
import com.kusej.idno.generation.utils.IDCardUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckIdCard {
    private JPanel contentPanel;
    private JTextField idNo;
    private JButton checkGoButton;
    private JTextField address;
    private JTextField birthday;
    private JTextField sex;
    private JLabel warning;
    private JTextField checkFlag;

    public CheckIdCard() {
        checkGoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                try {
                    String idNoText = idNo.getText();
                    if (StringUtils.isBlank(idNoText)) {
                        throw new RuntimeException("请输入证件号码！");
                    }
                    if (idNoText.length() != 18) {
                        throw new RuntimeException("sorry,目前仅支持18位身份证！");
                    }
                    String fullName = Global.code2FullName.get(idNoText.substring(0, 6));
                    address.setText(StringUtils.isBlank(fullName) ? String.format("区域代码(%s)未知", idNoText.substring(0, 6)) : fullName);
                    if (NumberUtils.toInt(idNoText.substring(10,12))<1 || NumberUtils.toInt(idNoText.substring(10,12))>12){
                        birthday.setText(String.format("错误(月份不正确):%s",idNoText.substring(6, 14)));
                    }else if (NumberUtils.toInt(idNoText.substring(12,14))<1 || NumberUtils.toInt(idNoText.substring(12,14))>31){
                        birthday.setText(String.format("错误(日期不正确):%s",idNoText.substring(6, 14)));
                    }else {
                        birthday.setText(idNoText.substring(6, 14));
                    }
                    sex.setText(NumberUtils.toInt(idNoText.substring(16, 17)) % 2 == 0 ? "女" : "男");
                    String checkCode = IDCardUtils.getCheckCode(idNoText);
                    checkFlag.setText(idNoText.substring(17).equals(checkCode) ? "正确" : String.format("错误(%s!=%s)",checkCode,idNoText.substring(17)));
                } catch (Exception e) {
                    e.printStackTrace();
                    Messages.showErrorDialog(e.getMessage(), "ERROR");
                }
            }
        });
    }

    public JComponent createUIComponents() {
        return contentPanel;
    }
}
